import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/pages/tab_mian_page.dart';
import 'package:flutter_app/utils/shared_preferences.dart';

class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  List<String> _guideList = [
    "assets/images/splash/guide_1_1.png",
    "assets/images/splash/guide_2_2.png",
    "assets/images/splash/guide_2_2.png"
  ];

  //屏幕的宽高
  double width;
  double height;
  SpUtil sp;

  List<String> pageList = ['PageView1', 'PageView2', 'PageView3'];
  int _currentPageIndex = 0;
  int _status = 0;
  Timer timer;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      sp = await SpUtil.getInstance();
      bool showWelcome = sp.getBool(SharedPreferencesKeys.showWelcome);
      if (showWelcome == null || showWelcome == false) {
        /// 预先缓存图片，避免直接使用时因为首次加载造成闪动
        _guideList.forEach((image) {
          precacheImage(AssetImage(image), context);
        });
      }
      _initSplash(showWelcome);
    });
  }

  _initSplash(showWelcome) {
    if (showWelcome == null || showWelcome == false) {
      _initGuide();
    } else {
      timer = Timer(const Duration(seconds: 3), () {
        //callback function

        toPage();
      });
    }
  }

  void _initGuide() {
    setState(() {
      _status = 1;
    });
  }

  toPage() async {
    sp.putBool(SharedPreferencesKeys.showWelcome, true);
    Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) {
      return TabMainPage();
    }), (route) => route == null);
  }

  _buildPageView() {
    return Center(
      child: Container(
        width: width,
        height: height,
        child: _status == 0
            ? Center(
                child: new Image(
                  image: new AssetImage('assets/images/splash/guide.gif'),
                  fit: BoxFit.fill,
                ),
              )
            : Stack(
                children: <Widget>[
                  PageView.builder(
                    onPageChanged: (int index) {
                      setState(() {
                        _currentPageIndex = index;
                      });
                    },
                    itemCount: _guideList.length,
                    scrollDirection: Axis.horizontal,
                    reverse: false,
                    itemBuilder: (context, index) {
                      return new ConstrainedBox(
                        child: new Image(
                          image: new AssetImage(_guideList[index]),
                          fit: BoxFit.fill,
                        ),
                        constraints: new BoxConstraints.expand(),
                      );
                    },
                  ),
                  _currentPageIndex == _guideList.length - 1
                      ? Align(
                          alignment: Alignment.bottomCenter,
                          child: Container(
                            margin: EdgeInsets.only(bottom: 20.0),
                            child: RaisedButton(
                              textColor: Colors.white,
                              color: Colors.indigoAccent,
                              // clipBehavior: Clip.antiAlias,
                              shape: RoundedRectangleBorder(
                                  // side: new BorderSide(
                                  //   width: 2.0,
                                  //   color: Colors.white,
                                  //   style: BorderStyle.solid,
                                  // ),
                                  // borderRadius: BorderRadius.only(
                                  //   topRight: Radius.circular(10.0),
                                  //   topLeft: Radius.circular(10.0),
                                  //   bottomLeft: Radius.circular(10.0),
                                  //   bottomRight: Radius.circular(10.0),
                                  // ),
                                  borderRadius: BorderRadius.circular(10.0)),
                              //BorderRadius.all(Radius.circular(10.0))),
                              child: Text(
                                '立即体验',
                                style: new TextStyle(fontSize: 16.0),
                              ),
                              onPressed: () => toPage(),
                            ),
                          ),
                        )
                      : Positioned(
                          bottom: 30,
                          left: 0,
                          right: 0,
                          child: Container(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: List.generate(_guideList.length, (i) {
                                return Container(
                                  margin: EdgeInsets.symmetric(horizontal: 5),
                                  width: 10,
                                  height: 10,
                                  decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      color: _currentPageIndex == i
                                          ? Colors.blue
                                          : Colors.grey),
                                );
                              }).toList(),
                            ),
                          ),
                        )
                ],
              ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    width = MediaQuery.of(context).size.width;
    height = MediaQuery.of(context).size.height;
    return _buildPageView();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    timer?.cancel();
  }
}
